<?php

namespace Sharks\Core\Http\Form;

use Sharks\Core\Http\Request;
use Sharks\Core\Persistence\QueryBuilder\Query;
use Sharks\Core\Support\Base\Str;

class QueryParamContainer {

    const WAY_EQUAL = "equal";
    const WAY_BETWEEN = "between";
    const WAY_LIKE = "like";

    private $params;

    public function __construct(Request $request) {
        $this->params = array();
        foreach ($request->inputs() as $formField) {
            if (Str::startsWith($formField, "query")) {
                $name = substr($formField, count("query"));
                $queryParam = new QueryParam($name, $request);
                $result[] = $queryParam;
            }
        }
    }

    public function getParams() {
        return $this->params;
    }

    public function getSelectQuery($class) {
        $query = Query::createSelect()->from($class);

        foreach ($this->params as $param) {
            $way = $param->getWay();
            if (self::WAY_EQUAL == $way) {
                $query->eq($param->getName(), $param->getValue());
            }
            elseif (self::WAY_BETWEEN == $way) {
                $query->between($param->getName(), $param->getRelatedValue("start"), $param->getRelatedValue("end"));
            }
            elseif (self::WAY_LIKE == $way) {
                $query->like($param->getName(), $param->getValue());
            }
        }

        return $query;
    }
}